package modbus

import (
	"fmt"
	"sync"
)

// ErrorMessageBuilder 错误消息构建器，复用字符串缓冲区
type ErrorMessageBuilder struct {
	buffer []byte
}

// errMsgBuilderPool 错误消息构建器对象池
var errMsgBuilderPool = &sync.Pool{
	New: func() interface{} {
		return &ErrorMessageBuilder{
			buffer: make([]byte, 0, 128), // 预分配128字节
		}
	},
}

// getErrorBuilder 获取错误消息构建器
func getErrorBuilder() *ErrorMessageBuilder {
	return errMsgBuilderPool.Get().(*ErrorMessageBuilder)
}

// putErrorBuilder 返回错误消息构建器
func putErrorBuilder(builder *ErrorMessageBuilder) {
	// 重置缓冲区长度但保留容量
	builder.buffer = builder.buffer[:0]
	// 只有合理大小的缓冲区才放回池中
	if cap(builder.buffer) <= 1024 {
		errMsgBuilderPool.Put(builder)
	}
}

// SlaveIDRangeError 从站ID范围错误（复用字符串）
func SlaveIDRangeError(slaveID, min, max byte) error {
	builder := getErrorBuilder()
	defer putErrorBuilder(builder)

	builder.buffer = fmt.Appendf(builder.buffer, "modbus: slaveID '%d' must be between '%d' and '%d'",
		slaveID, min, max)
	return fmt.Errorf("%s", string(builder.buffer))
}

// QuantityRangeError 数量范围错误（复用字符串）
func QuantityRangeError(quantity, min, max uint16) error {
	builder := getErrorBuilder()
	defer putErrorBuilder(builder)

	builder.buffer = fmt.Appendf(builder.buffer, "modbus: quantity '%d' must be between '%d' and '%d'",
		quantity, min, max)
	return fmt.Errorf("%s", string(builder.buffer))
}

// ResponseSizeError 响应大小错误（复用字符串）
func ResponseSizeError(actual, expected int) error {
	builder := getErrorBuilder()
	defer putErrorBuilder(builder)

	builder.buffer = fmt.Appendf(builder.buffer, "modbus: response data size '%d' does not match expected '%d'",
		actual, expected)
	return fmt.Errorf("%s", string(builder.buffer))
}

// ResponseCountError 响应计数错误（复用字符串）
func ResponseCountError(actual, expected int) error {
	builder := getErrorBuilder()
	defer putErrorBuilder(builder)

	builder.buffer = fmt.Appendf(builder.buffer, "modbus: response byte size '%d' does not match count '%d'",
		actual, expected)
	return fmt.Errorf("%s", string(builder.buffer))
}

// ResponseQuantityBytesError 响应数量字节错误（复用字符串）
func ResponseQuantityBytesError(actual uint8, expected uint16) error {
	builder := getErrorBuilder()
	defer putErrorBuilder(builder)

	builder.buffer = fmt.Appendf(builder.buffer, "modbus: response byte size '%d' does not match quantity to bytes '%d'",
		actual, expected)
	return fmt.Errorf("%s", string(builder.buffer))
}

// ResponseAddressError 响应地址错误（复用字符串）
func ResponseAddressError(actual, expected uint16) error {
	builder := getErrorBuilder()
	defer putErrorBuilder(builder)

	builder.buffer = fmt.Appendf(builder.buffer, "modbus: response address '%d' does not match request '%d'",
		actual, expected)
	return fmt.Errorf("%s", string(builder.buffer))
}

// ResponseValueError 响应值错误（复用字符串）
func ResponseValueError(actual, expected uint16) error {
	builder := getErrorBuilder()
	defer putErrorBuilder(builder)

	builder.buffer = fmt.Appendf(builder.buffer, "modbus: response value '%d' does not match request '%d'",
		actual, expected)
	return fmt.Errorf("%s", string(builder.buffer))
}

// ValueBitsSizeError 值位大小错误（复用字符串）
func ValueBitsSizeError(valueBits, quantity int) error {
	builder := getErrorBuilder()
	defer putErrorBuilder(builder)

	builder.buffer = fmt.Appendf(builder.buffer, "modbus: value bits size '%d' does not greater or equal to quantity '%d'",
		valueBits, quantity)
	return fmt.Errorf("%s", string(builder.buffer))
}

// ValueLengthError 值长度错误（复用字符串）
func ValueLengthError(valueLen, expectedLen int) error {
	builder := getErrorBuilder()
	defer putErrorBuilder(builder)

	builder.buffer = fmt.Appendf(builder.buffer, "modbus: value length '%d' does not twice as quantity '%d'",
		valueLen, expectedLen)
	return fmt.Errorf("%s", string(builder.buffer))
}
